<template>
  <div class="m-0" style="width: 90%;"
       v-loading="pageLoading"
       element-loading-text="拼命加载中"
       element-loading-spinner="el-icon-loading">
    <h2 class="text-center">部门管理</h2>
    <el-container>
      <el-aside>
        <h3>企业部门</h3>
        <el-tree
          :data="departmentTree"
          :props="departmentDefaultProps"
          default-expand-all
          @node-click="handleDepartmentTreeNodeClick"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
            <!--阻止点击事件冒泡-->
          <span @click.stop="">
            <!--父级删除-->
            <el-popconfirm
              v-if="data.children != null"
              confirm-button-text="确认"
              cancel-button-text="不用了"
              icon="el-icon-info"
              icon-color="red"
              title="该企业下的部门也将删除，确认吗？"
              @onConfirm="() => departmentRemove(node, data)"
            >
              <el-button slot="reference" type="text" size="mini"
                         v-if="superAdmin==1"
              >删除该企业</el-button
              >
            </el-popconfirm>
            <!--子级删除-->
          <el-popconfirm
            v-else
            confirm-button-text="确认"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="删除该部门吗？"
            @confirm="departmentRemove(node, data)"
          >
            <el-button slot="reference" type="text" size="mini"
            >删除该部门</el-button
            >
          </el-popconfirm>
        </span>
      </span>
        </el-tree>
      </el-aside>
      <el-main>
        <el-form ref="newDepartment" :model="newDepartment" label-width="120px">
          <el-divider v-if="newDepartment.departmentLevel=='children'">部门名称</el-divider>
          <el-divider v-if="newDepartment.departmentLevel=='parent'">企业名称</el-divider>
          <el-tag v-if="editflag===false">添加状态</el-tag>
          <el-tag v-if="editflag===true">修改状态</el-tag>
          <el-form-item
            v-for="(department,index) in newDepartment.departmentName"
            :label="'部门名称' + index"
            :key="department.key"
            :prop="'departmentName.' + index + '.value'"
            :rules="{
            required: true, message: '部门名称不能为空', trigger: 'blur'
            }">
            <el-input
              placeholder="部门名称"
              v-model="department.companyName"
              style="width: 70%"
              clearable
              @clear="handleClear"
            ></el-input>
            <el-button class="m-l-10" @click.prevent="removeDepartmentInput(department)" type="danger" size="mini">删除
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addFormItem('')"
                       :disabled="editflag">新增部门输入
            </el-button>
            <el-button type="primary" @click="addNewDepartment(newDepartment)"
                       :disabled="editflag"
            >提交新增
            </el-button
            >
            <el-button type="primary" @click="updateNewDepartment(newDepartment)"
                       v-if="editflag"
            >提交修改
            </el-button
            >
          </el-form-item>
        </el-form>
        <span
        >修改操作tips：点击想要修改的企业或部门，在右边表单进行修改，点击修改按钮即可。</span
        >
      </el-main>
    </el-container>
  </div>
</template>

<script>
  import {mapGetters} from "vuex";
  import {
    getDepartMentListAsTree,
    updateDepartMentByDepartMentId,
    addDepartMent,
    deleteCompany,
  } from "./departmentManage.js"

  export default {
    name: "departmentManagement",
    computed: {
      ...mapGetters([
        'roles'
      ])
    },
    data() {
      return {
        pageLoading: false,
        /*部门管理对话框*/
        departmentTree: [
          {
            label: 'name',
            // children:[],
          },
          {
            label: 'name',
            // children:[],
          }
        ],
        superAdmin: undefined,
        departmentDefaultProps: {
          // children: "children",
          label: "label",
        },
        newDepartment: {
          departmentLevel: "parent",
          parentNodes: [],
          companyId: "",
          pid: "",
          departmentName: [{
            companyName: "",
          }],
        },
        editflag: false,
      }
    },
    watch: {},
    created() {
      this.getDepartmenTree();

    },
    computed: {
      ...mapGetters([
        'roles'
      ])
    },
    methods: {
      /*部门管理*/
      handleClear() {
        this.editflag = false;
      },
      /*获取部门树*/
      getDepartmenTree() {
        /*获取企业树*/
        const _this = this;
        _this.pageLoading = true;
        getDepartMentListAsTree().then((response) => {
          if (response.data.hasOwnProperty("data") == true) {
            /*企业部门树赋值*/
            this.departmentTree = response.data.data;
            /*企业选择列表生成*/
            this.newDepartment.parentNodes = [];
            this.departmentTree.forEach(function (parentnode, indexx) {
              _this.newDepartment.parentNodes.push(parentnode);
            });
          }
          _this.pageLoading = false;
        })

      },
      /*部门树节点点击处理事件*/
      handleDepartmentTreeNodeClick(node, data) {
        this.editflag = true;
        // 用户是超级管理员
        if (data.level == 2) {
          /*点击节点是部门*/
          if (this.newDepartment.departmentName[0].value != "") {
            /*若第一条输入框存在数据，且编辑表示为false*/
            this.$confirm('正在添加部门中，是否清除已填写的数据?', '提示', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.newDepartment.departmentName = [{companyName: node.label}]
              this.newDepartment.companyId = node.id;
              this.$message({
                type: 'success',
                message: '清除成功，请点击修改!'
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消修改'
              });
            });
          } else {
            this.newDepartment.departmentName = [{companyName: node.label}]
            this.newDepartment.companyId = node.id;
            this.newDepartment.pid = data.parent.data.id
          }
        } else if (data.level == 1) {
          //点击的是企业节点
          if (this.editflag == true) {
            this.newDepartment.companyId = node.id;
            this.newDepartment.departmentName = [{companyName: node.label}]
            this.newDepartment.pid = 0;
          }
        }

      },
      /*部门树节点删除*/
      departmentRemove(node, data) {
        const _this = this;
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex((d) => d.id === data.id);
        children.splice(index, 1);
        //删除节点接口：
        deleteCompany(data.id).then((response) => {
          this.getDepartmenTree();
        })
      },
      departmentHandler(val) {
      },
      addNewDepartment(newDepartment) {
        var names = [];
        if (newDepartment.departmentName.length != 0) {
          newDepartment.departmentName.forEach(function (item, index) {
            if (item.companyName != "") {
              names.push({companyName: item.companyName});
            }
          })
        }
        var addData = {
          "departmentNames": names,
        }
        addDepartMent(addData).then((response) => {
          this.newDepartment.departmentName = [{
            companyName: "",
          }];
          this.getDepartmenTree();
        })
      },
      updateNewDepartment(newDepartment) {
        var updateData = {
          "companyId": newDepartment.companyId,
          "companyName": newDepartment.departmentName[0].companyName,
        }
        updateDepartMentByDepartMentId(updateData).then((response) => {
          this.getDepartmenTree();
          this.newDepartment.departmentName = [{companyName: ""}]
          this.editflag = false;
        })
      },
      addFormItem(value, id) {
        this.newDepartment.departmentName.push({
          companyName: value,
          key: Date.now()
        });
      },
      removeDepartmentInput(item) {
        var index = this.newDepartment.departmentName.indexOf(item)
        if (index !== -1) {
          if (this.newDepartment.departmentName.length != 1) {
            this.newDepartment.departmentName.splice(index, 1);
          } else {
            this.$message({
              message: '至少存在一条输入框',
              type: 'warning'
            });
          }
        }
      }
    },
  }
</script>

<style scoped>
  @import "../../styles/common.css";

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
